package com.binance.dynamodb.config;

import com.binance.dynamodb.constant.EnvValue;
import com.binance.dynamodb.rule.DefaultDynamodbTableRule;
import com.binance.dynamodb.rule.DynamodbTableRuleSelector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.amazonaws.auth.EC2ContainerCredentialsProviderWrapper;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;

import lombok.extern.log4j.Log4j2;


@Configuration
@EnableConfigurationProperties(AmazonDynamoDBProperties.class)
@ConditionalOnClass(AmazonDynamoDB.class)
@ConditionalOnProperty(name = "com.binance.amazon.dynamodb.enabled", havingValue = "true")
@Log4j2
public class AmazonDynamoDBAutoConfiguration {
    @Autowired
    private AmazonDynamoDBProperties dynamoDBProperties;

    @Bean
    public AmazonDynamoDB amazonDynamoDB() {
        final AmazonDynamoDBProperties.Endpoint endpoint = dynamoDBProperties.getEndpoint();
        AmazonDynamoDB amazonDynamoDB;
        try {
            // 针对本地启动dynamodb使用这个，需要.aws目录下有账号密码
            amazonDynamoDB = AmazonDynamoDBClientBuilder.standard()
                    .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint.getServiceEndpoint(),
                            endpoint.getSigningRegion()))
                    .build();
        } catch (Exception e) {
            log.info("can't find aws credentials file");
            // 服务器上面用这种基于role的实例化方式，需要运维配置
            final Regions regions = Regions.fromName(endpoint.getSigningRegion());
            amazonDynamoDB = AmazonDynamoDBClientBuilder.standard()
                    .withCredentials(new EC2ContainerCredentialsProviderWrapper()).withRegion(regions).build();
        }
        return amazonDynamoDB;
    }

    @Bean
    public DefaultDynamodbTableRule defaultDynamodbTableRule() {
        DefaultDynamodbTableRule defaultDynamodbTableRule = new DefaultDynamodbTableRule();
        return defaultDynamodbTableRule;
    }

    @Bean
    public DynamodbTableRuleSelector dynamodbTableRuleSelector() {
        DynamodbTableRuleSelector dynamodbTableRuleSelector = new DynamodbTableRuleSelector();
        return dynamodbTableRuleSelector;
    }

    @Bean
    public EnvValue envValue() {
        EnvValue envValue = new EnvValue();
        return envValue;
    }


}
